import {
  configure,
  start,
  done
} from 'nprogress' // progress bar
import {
  getSystemName
} from "@/common/js/utils"
import 'nprogress/nprogress.css'
import {
  apiInnerPointLogin,
  apiOperationLogCreate
} from '@/api'
configure({
  showSpinner: false
})

async function routerFilter(to, from, next) {
  start()
  let systemName = getSystemName();
  if (to.meta && to.meta.title) {
    document.title = systemName + "-" + to.meta.title;
  }

  if (to.query.enterpriseid) {
    sessionStorage.setItem('optEnterpriseid', to.query.enterpriseid);
  }

  if (to.query.selectProjectKey) {
    localStorage.setItem('projectKey', to.query.selectProjectKey);
  }

  // 非同域名页面跳转走内部单点
  if (to.query.token && to.query.isPointLogin) {
    let res = await apiInnerPointLogin(to.query.token)
    setStorage(res)
    if (res.extend.token) {
      let query = Object.assign({}, to.query);
      delete query['token'];
      delete query['isPointLogin'];
      next({
        path: to.path,
        query: query
      })
    } else {
      done()
    }
  }

  if (to.meta && to.meta.noAuth) {
    createlog(to)
    next()
  } else {
    let token = window.yj.getToken();
    // 开发者环境下，直接进入路由跳转
    if (!token && !to.query.source) {
      window.location.href = '/login'
      done()
    }
    createlog(to)
    next()
  }
}

//记录日志
async function createlog(to) {
  let userInfo = JSON.parse(localStorage.getItem('userInfo'));
  let systemName = getSystemName();
  let res = await apiOperationLogCreate({
    sourceType: "client", //日志来源
    operationType: "glanceOver", //操作类型
    userId: userInfo.key, //用户ID
    userName: userInfo.nickname, //用户名称
    requestUrl: location.href, //请求路径
    operationTime: new Date().getTime(), //创建时间
    operationDesc: systemName + "-" + to.meta.title, //操作描述
  })
}

function setStorage(res) {
  localStorage.setItem("userInfo", JSON.stringify(res));
  localStorage.setItem("token", res.extend.token);
  localStorage.setItem('publicKey', JSON.stringify(res.extend.publicKey));
  localStorage.setItem('roleCode', res.extend.roleCode ? JSON.stringify(res.extend.roleCode) : '');
  localStorage.setItem('authorities', res.extend.menuList ? JSON.stringify(res.extend.menuList) : '');
  localStorage.setItem('authorityCode', res.extend.roleCode ? JSON.stringify(res.extend.roleCode) : '');
  localStorage.removeItem('APP_MENU_DATA')
}

export default routerFilter
